"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));

/**
 * 查找满足条件的节点路径
 *
 * @since 0.0.5
 * @category 树算法
 * @param {array} treeList 树形结构集合.
 * @param {any|function} param 唯一key或者校验函数.
 * @param {object} config 配置参数.
 * @param {boolean} config.props 属性配置
 * @param {string} config.props.prop 数据的唯一主键key, 默认: id.
 * @param {string} config.props.childrenProp 数据的子主键key, 默认: children.
 *
 * @returns { array<PathResult> } 全路径
 *
 * @typedef {object} PathResult
 * @property {string} [prop] 校验结果
 * @property {number} index 所在位置下标
 *
 * @example
 *
 * z.treeFindPaths([{ id: 1, children: [{ id: 3, parentId: '1' , children: [{ id: 4, parentId: 3 }]}] }, { id: 2 }], 4)
 * // => [ { id: 1, index: 0 }, { id: 3, index: 0 }, { id: 4, index: 0 } ]
 *
 * z.treeFindPaths([{ code: 1, list: [{ code: 3, pCode: '1' , list: [{ code: 4, pCode: 3 }]}] }, { code: 2 }], 4, { props: { prop: 'code', childrenProp: 'list' } })
 * // => [ { id: 1, index: 0 }, { id: 3, index: 0 }, { id: 4, index: 0 } ]
 *
 */
function treeFindPaths(treeList, param) {
  var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
      _ref$props = _ref.props;

  _ref$props = _ref$props === void 0 ? {} : _ref$props;
  var _ref$props$prop = _ref$props.prop,
      prop = _ref$props$prop === void 0 ? 'id' : _ref$props$prop,
      _ref$props$childrenPr = _ref$props.childrenProp,
      childrenProp = _ref$props$childrenPr === void 0 ? 'children' : _ref$props$childrenPr;
  var callback = param;

  if (typeof callback !== 'function') {
    callback = function callback(node) {
      return node[prop] === param;
    };
  }

  var func = function func(array) {
    var paths = [];

    for (var i = 0; i < array.length; i++) {
      var item = array[i];
      var rt = callback(item);

      if (rt) {
        var _paths$push;

        paths.push((_paths$push = {}, (0, _defineProperty2.default)(_paths$push, prop, item[prop]), (0, _defineProperty2.default)(_paths$push, "index", i), _paths$push));
        return paths;
      }

      if (item[childrenProp]) {
        var _rt = func(item[childrenProp]);

        if (_rt) {
          var _context, _ref2;

          paths.push.apply(paths, (0, _concat.default)(_context = [(_ref2 = {}, (0, _defineProperty2.default)(_ref2, prop, item[prop]), (0, _defineProperty2.default)(_ref2, "index", i), _ref2)]).call(_context, (0, _toConsumableArray2.default)(_rt)));
          return paths;
        }
      }
    }
  };

  return func(treeList);
}

module.exports = treeFindPaths;